package com.example.demos.web.controller;

import com.example.demos.entity.Emp;
import com.example.demos.service.EmpService;
import com.example.demos.util.Result;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@RestController
public class LoginController {
    @Autowired
    private EmpService empService;

    @GetMapping("/")
    public ModelAndView index() {
        return new ModelAndView("login.html");
    }

    @PostMapping("/v2/login")
    public Result<Void> login(String username, String pwd, HttpSession session) {
        if (empService.checkLogin(username, pwd, session)) {
            return Result.ok("登录成功");
        } else {
            return Result.notLoginError();
        }
    }

    @PostMapping("/v2/login_showName")
    public Result<?> loginShowName(HttpSession httpSession) {
        return Result.ok(httpSession.getAttribute("username"), "ok");
    }

    @GetMapping("/v2//login_loginOut")
    public Result<?> logout(HttpSession httpSession) {
        httpSession.invalidate();
        return Result.ok();
    }

    @PostMapping("/v2/updatepwd")
    public Result<Void> updatePwd(String oldPwd, String newPwd, HttpSession session) {
        int flag = empService.updatePwd(oldPwd, newPwd, session);
        return flag == 1 ? Result.ok("修改成功") :
                flag == -1 ? Result.bizErr("旧密码错误"):
                Result.bizErr("新密码输入错误或为空，修改失败");
    }
}
